package net.ib.mtalk.ui.buddy.group;

import net.ib.mtalk.R;
import net.ib.mtalk.base.BaseFragmentActivity;
import net.ib.mtalk.database.DatabaseContract.GroupTable;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class EditGroup extends BaseFragmentActivity implements OnClickListener{
	
	private Context mContext;
	private EditGroupController mUiController;
	public static String GroupName = "groupname";
	public static String GroupId = "groupid";
	
	public static int GroupCreate = 1;
	public static int GroupChange = 2;
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			
		};
	};
	/*private List<GroupItem> list = new ArrayList<GroupItem>();
	private List<String> group_list = new ArrayList<String>();
	int count = -1;
	LinearLayout layout;
	LinearLayout[] linearLayouts;
	EditText[] editTexts;
	Button[] buttons;
	public static int ID = 1;
	public static int COUNT = 2;

	public static int NONE = 3;
	public static int CREATE = 4;
	public static int CHANGE = 5;
	public static int DELETE = 6;*/
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_group);
		
		mContext = this;
		mUiController = new EditGroupController(this, mHandler);
		
		FragmentManager fm = getSupportFragmentManager();
		
		if(savedInstanceState == null) {
			EditGroupFragment list = new EditGroupFragment();
			fm.beginTransaction().add(R.id.group_list, list).commit();
		}
		
		Button btn_add_group = (Button) findViewById(R.id.btn_add_group);
		Button btn_end_edit_group = (Button) findViewById(R.id.btn_end_edit_group);
		
		btn_add_group.setOnClickListener(this);
		btn_end_edit_group.setOnClickListener(this);
		/*layout = (LinearLayout) findViewById(R.id.aeg_layout);
		
		
		linearLayouts = new LinearLayout[100];
		editTexts = new EditText[100];
		buttons = new Button[100];
		String selection = GroupTable._ID + "!='1'";
		Cursor cursor = mContext.getContentResolver().query(GroupTable.CONTENT_URI, GroupTable.PROJECTION, selection, null, GroupTable.KEY_GROUP_NAME);
		try{
			while(cursor.moveToNext()){
				GroupItem item = new GroupItem(cursor.getInt(cursor.getColumnIndexOrThrow(GroupTable._ID)),
											cursor.getString(cursor.getColumnIndexOrThrow(GroupTable.KEY_GROUP_NAME)));
				list.add(item);
				group_list.add(cursor.getString(cursor.getColumnIndexOrThrow(GroupTable.KEY_GROUP_NAME)));
			}
		} finally {
			cursor.close();
		}
		
		// 저장 되어있는 값 불러옴
		for(int i = 0; i < list.size() ; i ++){
			makeview(null);
			
			editTexts[count].setText(list.get(i).name);
			editTexts[count].setTag(NONE);				// 불러온 경우 상태변화 NONE
			Map<Integer, Integer> map = new HashMap<Integer, Integer>();
			map.put(ID, list.get(i).id);
			map.put(COUNT, count);
			buttons[count].setTag(map);
			layout.addView(linearLayouts[count]);
		}
		
		btn_add_group.setOnClickListener(this);
		
		btn_end_edit_group.setOnClickListener(this);*/
	}
	
	public static class EditGroupFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor>{
		
		private CursorAdapter mAdapter;
		private OnClickListener mListener = new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(v.getId() == R.id.iag_edit){
					Intent intent = new Intent(getActivity(), AddGroup.class);
					intent.putExtra(GroupName, ((EditText)v).getText().toString());
					intent.putExtra(GroupId, (Integer)v.getTag());
					startActivity(intent);
				}
			}
		};

		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);
			setHasOptionsMenu(true);
			
			getLoaderManager().initLoader(0, null, this);

			mAdapter = new EditGroupCursorAdapter(getActivity(), null, 0, mListener);
			setListAdapter(mAdapter);

		}
		
		
		@Override
		public Loader<Cursor> onCreateLoader(int id, Bundle args) {
			Uri groupUri = GroupTable.CONTENT_URI;
			String selection = GroupTable._ID+ ">'2'";
			String sortOrder = GroupTable.KEY_GROUP_NAME;
			return new CursorLoader(getActivity(), groupUri, GroupTable.PROJECTION, selection, null, sortOrder);
		}

		@Override
		public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
			mAdapter.swapCursor(data);
			
		}

		@Override
		public void onLoaderReset(Loader<Cursor> loader) {
			mAdapter.swapCursor(null);
			
		}
		
	}

	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.btn_add_group){
			Intent intent = new Intent(mContext, AddGroup.class);
//			intent.putExtra(GroupName, value);
			startActivity(intent);
		} else if(v.getId() == R.id.btn_end_edit_group){
				finish();
		}
	}
	
	/*@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK) {
			AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
			builder.setTitle(R.string.group_add)
				   .setMessage(R.string.group_confirm_save)
				   .setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							for(int i = 0 ; i <= count ; i++){
								GroupDatabaseHelper.insertGroup(mContext, editTexts[i].getText().toString());
								Log.i("ZOO", editTexts[i].getText().toString());
							}
						}
				   })
				   .setNegativeButton(R.string.no, null)
				   .show();
//			event.startTracking();
		}
		return super.onKeyDown(keyCode, event);
	}

	private void makeview(String groupName) {
		count++;
		linearLayouts[count] = new LinearLayout(mContext);
		editTexts[count] = new EditText(mContext);
		buttons[count] = new Button(mContext);
		
		linearLayouts[count] = (LinearLayout) View.inflate(mContext, R.layout.item_add_group, null);
		editTexts[count] = (EditText) linearLayouts[count].findViewById(R.id.iag_edit);
		buttons[count] = (Button) linearLayouts[count].findViewById(R.id.iag_delete_btn);
		
		Map<Integer, Integer> map = new HashMap<Integer, Integer>();
		map.put(COUNT, count);
		
		editTexts[count].setText(groupName);
		editTexts[count].setOnClickListener(this);
		buttons[count].setTag(map);
		
		buttons[count].setOnClickListener(this);
	}
	
	@Override
	public void onClick(final View v) {
		if(v.getId() == R.id.iag_delete_btn){
			removeGroup(v);
		} else if(v.getId() == R.id.btn_add_group){
			final EditText editText = new EditText(mContext);
			editText.setFocusable(true);
			editText.setHint(R.string.group_enter_group_name);
			AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
			builder.setTitle(R.string.group_add)
				   .setView(editText)
				   .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							if(!"".equals(editText.getText().toString())){	// 그룹 이름이 있을 경우
								if(group_list.contains(editText.getText().toString())){	//	생성한 그룹이 존재할 경우 
									Toast.makeText(mContext, R.string.group_exist_group, Toast.LENGTH_SHORT).show();	
								} else{	//	정상적으로 그룹생성
									makeview(editText.getText().toString());
									editTexts[count].setTag(CREATE);	// 새로 만든 경우 상태 CREATE
									layout.addView(linearLayouts[count]);
									group_list.add(editText.getText().toString());
								}
							} else {	// 그룹 이름이 없을 경우
								Toast.makeText(mContext, R.string.group_enter_group_name, Toast.LENGTH_SHORT).show();
							}
						}
				   })
				   .setNegativeButton(R.string.cancel, null)
				   .show();
		} else if(v.getId() == R.id.btn_end_edit_group){
			for(int i = 0 ; i <= count ; i++){
				if(!editTexts[i].getText().toString().equals("")){	// 남아있는 그룹만 변경
					GroupDatabaseHelper.insertGroup(mContext, editTexts[i].getText().toString());
					Log.i("ZOO", editTexts[i].getText().toString());
				} else{
//					GroupDatabaseHelper.deleteGroup(mContext);
				}
			}
			finish();
		} else if(v.getId() == R.id.iag_edit){
			final EditText editText = new EditText(mContext);
			editText.setFocusable(true);
			editText.setText(((EditText)v).getText());
			AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
			builder.setTitle(R.string.group_change_group_name)
				   .setView(editText)
				   .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							if(!"".equals(editText.getText().toString())){	// 그룹 이름이 있을 경우
								if(group_list.contains(editText.getText().toString())){		//	변경한 그룹이 존재할 경우 
									Toast.makeText(mContext, R.string.group_exist_group, Toast.LENGTH_SHORT).show();	
								} else{	// 정상적으로 그룹변경
									((EditText)v).setText(editText.getText());
									group_list.remove(((EditText)v).getText());
									group_list.add(editText.getText().toString());
									if((Integer)v.getTag() != CREATE){
										v.setTag(CHANGE);	// 변경한 경우, 상태 CHANGE
									}
								}
							} else {	// 그룹 이름이 없을 경우
								Toast.makeText(mContext, R.string.group_enter_group_name, Toast.LENGTH_SHORT).show();
							}
						}
				   })
				   .setNegativeButton(R.string.cancel, null)
				   .show();
		}
	}

	private void removeGroup(final View v) {
		final Map<Integer, Integer> map = (Map<Integer, Integer>) v.getTag();
//		String selection = ParticipantsTable.KEY_PARTICIPANTS_GROUP + "=?";
//		String selectionArgs[] = null;
//		Cursor cursor = getContentResolver().query(ParticipantsTable.CONTENT_URI, ParticipantsTable.PROJECTION, selection, selectionArgs, null);
		if(map.get(ID) != null){
			AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
			builder.setMessage(R.string.group_delete_confirm1);
			builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					editTexts[map.get(COUNT)].setText("");
					if((Integer)editTexts[map.get(COUNT)].getTag() == CREATE){
						editTexts[map.get(COUNT)].setTag(NONE);
					} else {
						editTexts[map.get(COUNT)].setTag(DELETE);
					}
					layout.removeView((View) v.getParent());
				}
			});
			builder.setNegativeButton(R.string.cancel, null);
			builder.show();
		} else{
			AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
			builder.setMessage(R.string.group_delete_confirm2);
			builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					editTexts[map.get(COUNT)].setText("");
					layout.removeView((View) v.getParent());
				}
			});
			builder.setNegativeButton(R.string.cancel, null);
			builder.show();
		}
	}*/
}
